package com.fise.mwtvc

import android.app.Instrumentation
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import android.view.KeyEvent
import com.fise.mwtvc.socket.WebSocketClient
import com.fise.mwtvc.socket.bean.WsKeyResponse
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.launch

/**
 * @author vincent
 * @date 2023/1/3.
 * email：jiaqiangmn@gmail.com
 * description：
 */
class MyService : Service() {
    private   val TAG = "MyService"
    private val webSocketClient by lazy { WebSocketClient() }
    private val ioScope = CoroutineScope(Dispatchers.IO)
    private val inst = Instrumentation();
    override fun onCreate() {
        super.onCreate()
        startWs();
    }

    @OptIn(InternalCoroutinesApi::class)
    private fun startWs() {
        ioScope.launch {
            webSocketClient.start().collect(object : FlowCollector<WsKeyResponse> {
                override suspend fun emit(value: WsKeyResponse) {
                    val keycode = value.getKeyCode();
                    Log.d(TAG, "keycode:$keycode")
                    if (keycode == -99) {
                        return
                    }
                    if (keycode == KeyEvent.KEYCODE_SETTINGS) {
                        sendCustom()
                        return
                    }
                    if (keycode == 404) {
                        shutdown();
                        return
                    }
                    try {
                        inst.sendKeyDownUpSync(keycode);
                    } catch (e: Exception) {
                        Log.e(TAG, "事件出现异常" + e.message);
                    }
                }
            })
        }
    }

    private fun sendCustom() {
        sendBroadcast(Intent("com.fise.menu.show"))
    }

    private fun shutdown() {
        sendBroadcast(Intent("com.fise.system.shutdown"))
    }

    override fun onBind(p0: Intent?): IBinder? {
        return null;
    }

}
